<template>
  <div id="loginForm">
    <header-sculture></header-sculture>
    <el-form :model="loginFormDate" ref="loginFormRef" :rules="formRules" class="form">
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input v-model="loginFormDate.username" prefix-icon="iconfont icon-yonghu"></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input v-model="loginFormDate.password" type="password" prefix-icon="iconfont icon-suo"></el-input>
      </el-form-item>

      <!-- 登陆、重置按钮 -->
      <el-row class="LoginForm-button_right">
        <el-button type="primary" @click="login">登陆</el-button>
        <el-button el-button type="info" @click="reset">重置</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
// 组件
import headerSculture from "components/login/HeaderSculture";
// 组件结束

// 请求
import { getLogin } from "@/network/loginRequest.js";

export default {
  name: "loginForm",
  data() {
    return {
      // v-model登陆表单数据
      loginFormDate: {
        username: "jybill",
        password: "123"
      },
      // 登陆表单规则
      formRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        userPwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    reset() {// 表单重置方法
      
      this.$refs["loginFormRef"].resetFields(); // el提供的重置方法
    },
    login() {// 表单登陆方法
      
      // 表单validate(callback); 执行回调内容
      this.$refs.loginFormRef.validate(async vali => {
        if (!vali) return alert("请检查账号密码再登陆");

        // 发送axios登陆请求
        const res = await getLogin(this.loginFormDate);
        // console.log(res);
        // 判断登陆成功、失败
        // console.log(res);
        if (res.meta.status !== 200) { // 状态码返回异常
          // 失败弹框
          this.$message.error({ // 失败执行弹框
            message: res.meta.msg,
            showClose: true,
            center: true
          });
          return;
        }

        // 登陆成功
        this.$message.success({ // 成功执行弹框
          message: "登陆成功",
          showClose: true,
          center: true
        });        
        
        // 登陆成功给token
        window.sessionStorage.setItem('token', res.data.token);
        
        this.$router.push({name: 'welcome'}); // 跳转到Home组件
      });
    }
  },
  components: {// 子组件
    headerSculture
  }
};
</script>

<style lang="scss" scoped>
#loginForm {
  background-color: $loginFormBackGroundColor;
  width: $loginFormWith;
  height: $loginFormHeight;

  @include absolute_center;
}

#loginForm .form {
  position: absolute;
  bottom: 12%;

  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.LoginForm-button_right {
  display: flex;
  justify-content: flex-end;
}
</style>